//该文件用于创建Vuex中最为核心的store
import {reqVerifIcation,reqPassport,reqLogin,reqUserInfo,reqLongOut} from '@/api'
import {setToken,getToken,removeToken} from '@/utils/token'
//准备actions一用于响应组件中的动作
const actions ={
    //获取验证码
    async getVerifIcation({commit},phone){
        let result = await reqVerifIcation(phone)
        if(result.code == 200){
            commit('GETVERIFICATION',result.data)
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
    //注册用户
    async reqPassport({commit},params){
        let result = await reqPassport(params)
        if(result.code == 200){
            return 'ok'
        }else{
            alert(`"注册失败！"${result.message}`)
            return Promise.reject(new Error('faile'))
        }
    },
    //用户登录
    async userLogin({commit},data){
        let result = await reqLogin(data)
        if(result.code == 200){
            commit("USERLOGIN",result.data.token)
            //本地持久化存储token
            setToken(result.data.token)
        }else{
            alert(result.message)
            return Promise.reject(new Error('faile'))
        }
    },
    //获取用户信息
    async getUserInfo({commit}){
        let result = await reqUserInfo()
        if(result.code == 200){
            commit("GETUSERINFO",result.data)
            return 'ok'
        }
        else{
            return Promise.reject(new Error('faile'))
        }
        //不判断错误就不返回错误了
    },
    //退出登录
    async reqLongOut({commit}){
        let result = await reqLongOut()
        if(result.code == 200){
            //清空本地仓库token
            removeToken()
            // 清空仓库的token 与用户信息
            commit("REQLONGOUT")
            return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
    }
}
//准备mutations.一用于操作数据(state)
const mutations ={
    //获取验证码
    GETVERIFICATION(state,verification){
        state.verification = verification
    },
    //登录返回信息 主要是token
    USERLOGIN(state,token){
        state.token = token
    },
    GETUSERINFO(start,userInfo){
        start.userInfo = userInfo
    },
    //清空token 与 用户信息
    REQLONGOUT(start){
        //清空token
        start.token = ""
        //清空用户信息
        start.userInfo = {}
    }
}
//准备state一用于存储数据
const state ={
    verification:'',
    //用户的token不想修改名字了
    token:getToken(),
    //用户信息
    userInfo:{}
}
//getters:理解为计算属性，用于简化仓库数据，让组件获取仓库的数据更加方便
const getters = {
}

//创建并暴露store
export default{
state,
mutations,
actions,
getters,
}